package cn.jly.flink.operators;

import cn.jly.flink.entity.SensorReading;
import cn.jly.flink.utils.FlinkUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @PackageName cn.jly.flink.operators
 * @ClassName ReduceDemo
 * @Description reduce测试
 * @Author 姬岚洋
 * @Date 2021/1/27 下午 2:37
 */
public class ReduceDemo {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = FlinkUtils.getStreamExecutionEnv();

        env.readTextFile("d:/SensorReading.txt")
                .flatMap(new FlatMapFunction<String, SensorReading>() {
                    @Override
                    public void flatMap(String value, Collector<SensorReading> collector) throws Exception {
                        if (StringUtils.isNotEmpty(value)) {
                            collector.collect(JSON.parseObject(value, SensorReading.class));
                        }
                    }
                })
                .keyBy(new KeySelector<SensorReading, String>() {
                    @Override
                    public String getKey(SensorReading value) throws Exception {
                        return value.getId();
                    }
                })
                .reduce(new ReduceFunction<SensorReading>() {
                    @Override
                    public SensorReading reduce(SensorReading s1, SensorReading s2) throws Exception {
                        // 永远更新为最新的时间戳
                        return new SensorReading(s1.getId(), s2.getTimestamp(), Double.max(s1.getTimestamp(), s2.getTemperature()));
                    }
                })
                .filter(new FilterFunction<SensorReading>() {
                    @Override
                    public boolean filter(SensorReading value) throws Exception {
                        return "1003".equals(value.getId());
                    }
                })
                .print("reduce");


        FlinkUtils.executeStream(env, "ReduceDemo");
    }
}
